package obecto.validation.data
{
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	import obecto.event.ValidatorEvent;
	
	[Event(name="valid", type="obecto.event.ValidatorEvent")]
	[Event(name="invalid", type="obecto.event.ValidatorEvent")]
	public class BooleanExpressionValidator extends EventDispatcher implements IDataValidator
	{
		private var _valid : Boolean = true;
		public function get valid() : Boolean
		{
			return _valid;
		}
		
		private var _data : Boolean;
		public function set data(value : Object) : void
		{
			if (value != _valid)
			{
				_data = value;
				validate();
			}
		}
		public function get data() : Object
		{
			return _valid;
		}
		
		private var _enabled : Boolean = true;
		public function set enabled(value : Boolean) : void
		{
			if (value != _enabled)
			{
				_enabled = value;
				if (_enabled)
				{
					validate();
				}
			}
		}
		public function get enabled():Boolean
		{
			return _enabled;
		}
		
		[Bindable]
		public var errorMessage : String;
		
		public function BooleanExpressionValidator(target : IEventDispatcher = null)
		{
			super(target);
		}
		
		public function validate(quiet : Boolean = false) : void
		{
			if (_enabled)
			{
				var oldValid : Boolean = _valid;
				var newValid : Boolean = _data;
				_valid = newValid
				
				var event : ValidatorEvent;
				if (newValid)
				{
					event = new ValidatorEvent(ValidatorEvent.VALID);
				}
				else
				{
					event = new ValidatorEvent(ValidatorEvent.INVALID);
				}
				
				if (!quiet && newValid != oldValid)
				{
					dispatchEvent(event);
				}
			}
		}
		
		public function reset() : void
		{
			_valid = true;
		}
		
	}
}